package com.sunny.ynhz.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sunny.ynhz.R;
import com.sunny.ynhz.api.NetUrl;
import com.sunny.ynhz.bean.VersionBean;
import com.sunny.ynhz.api.okhttp.OkHttpHelper;

import java.io.File;

import okhttp3.Request;

/**
 * Created by Administrator on 2016/9/9.
 */
public class CheckVersionUtlils {
    //  public static String url = "http://gzhzsp.sunnyhf.com:8090/";
    public static void getVersion(final Context context, final int type) {
        OkHttpHelper.getAsyn(context, NetUrl.baseUrl + "appversion/update", new OkHttpHelper.ResultCallback<VersionBean>() {
            @Override
            public void onError(Request request, Exception e) {
                if (type == 1) {
                    ShowUtils.closePopwindow();
                }
            }
            @Override
            public void onResponse(final VersionBean response) {
                if (response.getData().getVersion().compareTo(AppVersionUtils.getVersion(context))<=0) {
                    if (type == 1) {
                        ToastUtils.SingleToastUtil(context, "当前已是最新版本，无需更新!");
                    }
                    return;
                }
                final Dialog dialog = new Dialog(context, R.style.style_loading_dialog);
                View view = LayoutInflater.from(context).inflate(R.layout.diglog_version_update, null);
                TextView tv_version = (TextView) view.findViewById(R.id.update_version_tv);
                View tv_cancle = view.findViewById(R.id.tv_cancle);
                tv_cancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();

                    }
                });
                tv_version.setText(response.getData().getDescription());
                dialog.setContentView(view);
                if (response.getData().isIsforce()) {
                    dialog.setCancelable(false);
                    tv_cancle.setVisibility(View.INVISIBLE);
                }
                dialog.show();
                view.findViewById(R.id.tv_load_Apk).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String path = FileUtils.markFilePathString(context);
                        checkVersionUtlils(response.getData().getUrl(), context, path);
                        dialog.dismiss();

                    }
                });
            }

            @Override
            public void onBefore(Request request) {
                if (type == 1) {
                    ShowUtils.inItPopwin(context, "正在连接服务器，检测本机版本请稍后...");
                }
            }

            @Override
            public void onAfter() {
                if (type == 1) {
                    ShowUtils.closePopwindow();
                }
            }
        });
    }


    public static void checkVersionUtlils(String url, final Context context, String path) {
        final Dialog dialog = new Dialog(context, R.style.style_loading_dialog);
        dialog.setCancelable(false);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_downprg, null);
        final ProgressBar progressBar =view.findViewById(R.id.progressbar);
        final TextView tv_number =view.findViewById(R.id.update_number_tv);
        final TextView tv_progrss = view.findViewById(R.id.update_number_progress);
        dialog.setContentView(view);
        dialog.show();
        dialog.setCancelable(false);
        OkHttpHelper.DownloadDelegate downloadDelegate = OkHttpHelper.getDownloadDelegate();
        downloadDelegate.downloadAsyn(url, path, new OkHttpHelper.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                installApp(context, response);
            }

            @Override
            public void onProgressUpdate(long bytesRead, long contentLength, boolean done) {
                int progrss = (int) (((float) bytesRead / contentLength) * 100);
                progressBar.setProgress(progrss);
                tv_number.setText(progrss + "%");
                tv_progrss.setText(progrss + "/" + 100);
            }

            @Override
            public void onAfter() {
                dialog.dismiss();
            }
        });
    }

    private static void installApp(Context context, String path) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * get App versionName
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        String versionName = "";
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }
}